package com.gmrz.uap.uasconfig;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cache.CacheStoreService;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ServiceSupport;
import com.gmrz.uap.model.Facets;
import com.gmrz.uap.model.Tenant;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.user.UserController;
import com.gmrz.uap.util.IOUtils;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ouhouki on 16/8/31.
 */
public class UasConfigService extends ServiceSupport {

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    public static final UasConfigService me = new UasConfigService();


    public Page<UasConfig> findListPaginate(UasConfig uasConfig, int page, int rows, String sort, String order) {
        return UasConfig.dao.findListPaginate(uasConfig, page, rows, sort, order);
    }

    /**
     * 恢复默认配置
     *
     * @param configType 配置类型'1'为系统配置,'2'为redis配置
     */
    public int sysBack2Default(Integer configType, String tentanid) {
        int i = UasConfig.dao.sysBack2Default(configType);
        if (i > 0) {
            //重写uas.properties文件
            UasConfigService.me.write2UasFile(tentanid);
        }
        return i;
    }

    /**
     * 读取配置信息,并写到配置路径处
     */
    public boolean write2UasFile(String tenantid) {
        boolean flag = true;
        ArrayList<UasConfig> configList = new ArrayList<UasConfig>(UasConfig.dao.getConfigList(null));
        StringBuilder sb = new StringBuilder();
        List<Facets> allFacets = Facets.dao.findAll(tenantid);
        if (allFacets != null && allFacets.size() > 0) {
            for (int x = 0; x < allFacets.size() - 1; x++) {
                sb.append(allFacets.get(x).getFacetName() + ",");
            }
            sb.append(allFacets.get(allFacets.size() - 1).getFacetName());
        }
        UasConfig uasConfig = new UasConfig();
        uasConfig.setConfigEname("uaf.facet.id");
        uasConfig.setConfigValue(sb.toString());
        configList.add(1, uasConfig);
        sb.delete(0, sb.length());
        for (UasConfig c : configList) {
            sb.append(c.getConfigEname() + "=" + c.getConfigValue() + "\n");
        }
        IOUtils.String2File(sb.toString(), new File(PathKit.getWebRootPath() + "/download/", "uaf.properties"));

        try {
            //将信息存放到缓存中
            CacheStoreService cacheStoreService = AmmsCacheUtil.getCacheStoreService();
            cacheStoreService.set(AmmsCacheUtil.UAFFACETID, getFacetsByTentanid());
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


//    public void test(){
//        System.out.println(getFacetsByTentanid());
//    }

    public String getFacetsByTentanid() {

        List<Tenant> allTenants = Tenant.dao.getAllTenants();

        Map<String, String> facets = new HashMap<String, String>();
        StringBuilder buf = null;

        LOG.info("根据不同的租户将手机应用ID放进缓存");

        for (Tenant a : allTenants) {
            String tenantid = a.getTenantId();
            if (tenantid != null) {
                List<Facets> allFacets = Facets.dao.findAll(tenantid);
                buf = new StringBuilder();
                if (allFacets != null && allFacets.size() > 0) {
                    for (int i = 0; i < allFacets.size(); i++) {
                        Facets facetsTmp = allFacets.get(i);
                        buf.append(facetsTmp.getFacetName());

                        if (i != (allFacets.size() - 1)) {
                            buf.append(";");
                        }
                    }
                }
                LOG.info("租户 = " + tenantid + "     手机应用 = " + buf.toString());
                facets.put(tenantid, buf.toString());
            }
        }
        LOG.info("uaf.facet.id = " + facets.toString());
        return facets.toString();
    }

    /**
     * 获取用户可配置属性列表
     *
     * @return 配置列表
     */
    public List<UasConfig> getUserDefinedList(Integer confingType) {
        return UasConfig.dao.getConfigList(confingType);
    }

    /**
     * 根据id更新配置
     *
     * @param uasConfig 配置信息
     */
    public boolean updateSysCongfig(UasConfig uasConfig, String tenantid) {

        if (uasConfig.getConfigValue() == null) {
            uasConfig.setConfigValue("");
        }

        uasConfig.setUpdatets(new Timestamp(new DateTime().getMillis()));
        flag = uasConfig.update();

        if (flag) {
            //重写uaf.properties文件
            write2UasFile(tenantid);
        }
        return flag;
    }


    /**
     * 根据属性键更新属性默认值信息
     *
     * @param tenantId   租户ID
     * @param uasConfigs 需要更新的配置信息
     * @return boolean  是否成功
     */
    public boolean editDefaultValueByKey(String tenantId, List<UasConfig> uasConfigs) {
        boolean flag = false;
        int num = UasConfig.dao.updateDefaultValueByKey(tenantId, uasConfigs);

        flag = num > 0;

        return flag;
    }

    public int getMaxPolicyValue() {
        int i = 0;
        try {
            i = Integer.parseInt(UasConfig.dao.getValueByKey(SystemConst.MAX_NUM_POLICY_AAID));
        } catch (NumberFormatException e) {
        }
        return i;
    }


    public List<UasConfig> getConfigListByType(Integer confingType) {
        return UasConfig.dao.getConfigListByType(confingType);
    }

}
